#!/bin/bash

# 全球SSL访问诊断脚本
# 诊断不同地区访问SSL网站的问题

set -e

# 颜色输出
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

log_info() {
    echo -e "${GREEN}[INFO]${NC} $1"
}

log_warn() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

log_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

print_title() {
    echo -e "${BLUE}"
    echo "=================================================="
    echo "    全球SSL访问诊断工具"
    echo "=================================================="
    echo -e "${NC}"
}

# 检查域名解析
check_dns_resolution() {
    log_info "检查域名解析..."
    
    local domains=("pecco.pet" "www.pecco.pet")
    
    for domain in "${domains[@]}"; do
        echo "检查域名: $domain"
        
        # 使用多个DNS服务器检查
        for dns in "8.8.8.8" "1.1.1.1" "208.67.222.222" "9.9.9.9"; do
            echo "  DNS $dns: $(dig @$dns +short $domain | head -1)"
        done
        echo
    done
}

# 检查SSL证书
check_ssl_certificate() {
    log_info "检查SSL证书..."
    
    local domains=("pecco.pet" "www.pecco.pet")
    
    for domain in "${domains[@]}"; do
        echo "检查域名: $domain"
        
        # 检查证书有效性
        if openssl s_client -connect $domain:443 -servername $domain -verify_return_error < /dev/null 2>/dev/null; then
            echo "  ✓ SSL证书有效"
        else
            echo "  ✗ SSL证书验证失败"
        fi
        
        # 检查证书过期时间
        expiry=$(echo | openssl s_client -connect $domain:443 -servername $domain 2>/dev/null | openssl x509 -enddate -noout 2>/dev/null | cut -d= -f2)
        echo "  过期时间: $expiry"
        
        # 检查证书链
        echo "  证书链检查:"
        openssl s_client -connect $domain:443 -servername $domain -showcerts < /dev/null 2>/dev/null | grep -c "BEGIN CERTIFICATE" | xargs echo "    证书数量:"
        
        echo
    done
}

# 检查HTTP/HTTPS重定向
check_redirects() {
    log_info "检查HTTP/HTTPS重定向..."
    
    local test_urls=(
        "http://pecco.pet"
        "http://www.pecco.pet"
        "https://pecco.pet"
        "https://www.pecco.pet"
    )
    
    for url in "${test_urls[@]}"; do
        echo "测试: $url"
        
        # 获取HTTP状态码和重定向位置
        response=$(curl -s -I -L --max-redirs 5 "$url" 2>/dev/null || echo "连接失败")
        
        if [[ "$response" == "连接失败" ]]; then
            echo "  ✗ 连接失败"
        else
            status=$(echo "$response" | head -1 | awk '{print $2}')
            location=$(echo "$response" | grep -i "location:" | head -1 | cut -d' ' -f2- | tr -d '\r')
            
            echo "  状态码: $status"
            if [[ -n "$location" ]]; then
                echo "  重定向到: $location"
            fi
        fi
        echo
    done
}

# 检查网络连通性
check_network_connectivity() {
    log_info "检查网络连通性..."
    
    local server_ip="124.220.186.165"
    local ports=(80 443)
    
    echo "服务器IP: $server_ip"
    
    for port in "${ports[@]}"; do
        echo "检查端口 $port:"
        
        if nc -z -w5 $server_ip $port 2>/dev/null; then
            echo "  ✓ 端口 $port 可达"
        else
            echo "  ✗ 端口 $port 不可达"
        fi
    done
    echo
}

# 检查SSL配置评级
check_ssl_rating() {
    log_info "SSL配置建议..."
    
    echo "建议使用以下在线工具检查SSL配置:"
    echo "1. SSL Labs: https://www.ssllabs.com/ssltest/analyze.html?d=pecco.pet"
    echo "2. SSL Labs: https://www.ssllabs.com/ssltest/analyze.html?d=www.pecco.pet"
    echo "3. Security Headers: https://securityheaders.com/?q=https://pecco.pet"
    echo
}

# 检查全球DNS传播
check_global_dns() {
    log_info "全球DNS传播检查..."
    
    echo "建议使用以下工具检查全球DNS传播:"
    echo "1. What's My DNS: https://www.whatsmydns.net/#A/pecco.pet"
    echo "2. What's My DNS: https://www.whatsmydns.net/#A/www.pecco.pet"
    echo "3. DNS Checker: https://dnschecker.org/#A/pecco.pet"
    echo
}

# 生成修复建议
generate_fix_suggestions() {
    log_info "修复建议..."
    
    echo "基于常见的欧洲访问问题，建议："
    echo
    echo "1. 证书兼容性问题："
    echo "   - 确保使用完整的证书链"
    echo "   - 检查中间证书是否正确配置"
    echo
    echo "2. DNS解析问题："
    echo "   - 等待DNS全球传播完成（最多48小时）"
    echo "   - 考虑使用CDN服务"
    echo
    echo "3. 网络连通性问题："
    echo "   - 检查服务器防火墙设置"
    echo "   - 确认云服务商安全组配置"
    echo
    echo "4. 浏览器安全警告："
    echo "   - 提交网站到安全数据库白名单"
    echo "   - Microsoft SmartScreen: https://www.microsoft.com/en-us/wdsi/support/report-unsafe-site"
    echo "   - Google Safe Browsing: https://safebrowsing.google.com/safebrowsing/report_error/"
    echo
    echo "5. 立即修复命令："
    echo "   docker-compose -f docker-compose.prod.yml restart nginx"
    echo "   curl -I https://pecco.pet"
    echo "   curl -I https://www.pecco.pet"
}

# 主函数
main() {
    print_title
    
    check_dns_resolution
    check_network_connectivity
    check_ssl_certificate
    check_redirects
    check_ssl_rating
    check_global_dns
    generate_fix_suggestions
    
    echo -e "${GREEN}诊断完成！${NC}"
    echo "请将诊断结果发送给欧洲客户，并建议他们："
    echo "1. 清除浏览器缓存和DNS缓存"
    echo "2. 尝试使用不同的浏览器"
    echo "3. 使用手机网络而非WiFi测试"
    echo "4. 等待24-48小时后重试"
}

# 运行主函数
main "$@"
